<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- ===== 核心搜索条件（常用） ===== -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="PoolId_FormItem" prop="PoolId">
							<template #label>
								<WtmLabelTooltip label="需求池" tooltip="关联的需求池主表" />
							</template>
							<el-select v-model="searchData.PoolId" :data="stateData.AllSysPurchaseRequirementPools" clearable>
								<el-option
									v-for="item in stateData.AllSysPurchaseRequirementPools"
									:key="item.Value"
									:value="item.Value"
									:label="item.Text"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="RequestBillId_FormItem" prop="RequestBillId">
							<template #label>
								<WtmLabelTooltip label="采购申请单" tooltip="关联的采购申请单主表" />
							</template>
							<el-select v-model="searchData.RequestBillId" :data="stateData.AllSysPurchaseRequestBills" clearable>
								<el-option v-for="item in stateData.AllSysPurchaseRequestBills" :key="item.Value" :value="item.Value" :label="item.Text"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="MaterialId_FormItem" prop="MaterialId">
							<template #label>
								<WtmLabelTooltip label="物料" tooltip="采购的物料" />
							</template>
							<el-select v-model="searchData.MaterialId" :data="stateData.AllSysMaterials" clearable>
								<el-option v-for="item in stateData.AllSysMaterials" :key="item.Value" :value="item.Value" :label="item.Text"></el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<!-- ===== 高级搜索条件（可展开） ===== -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="PurchaseState_FormItem" prop="PurchaseState">
								<template #label>
									<WtmLabelTooltip label="采购状态" tooltip="采购状态：待立项、立项中、已立项、已取消" />
								</template>
								<el-select v-model="searchData.PurchaseState" clearable>
									<el-option key="待立项" value="待立项" label="待立项"></el-option>
									<el-option key="立项中" value="立项中" label="立项中"></el-option>
									<el-option key="已立项" value="已立项" label="已立项"></el-option>
									<el-option key="已取消" value="已取消" label="已取消"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="PurchaseType_FormItem" prop="PurchaseType">
								<template #label>
									<WtmLabelTooltip label="采购类型" tooltip="采购类型：常规、设备新增、安全新增等" />
								</template>
								<el-select v-model="searchData.PurchaseType" clearable>
									<el-option key="常规" value="常规" label="常规"></el-option>
									<el-option key="设备新增" value="设备新增" label="设备新增"></el-option>
									<el-option key="安全新增" value="安全新增" label="安全新增"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="MaterialType_FormItem" prop="MaterialType">
								<template #label>
									<WtmLabelTooltip label="物料类型" tooltip="物料类型：备品备件、化工小料、大宗原材料" />
								</template>
								<el-select v-model="searchData.MaterialType" clearable>
									<el-option key="备品备件" value="备品备件" label="备品备件"></el-option>
									<el-option key="化工小料" value="化工小料" label="化工小料"></el-option>
									<el-option key="大宗原材料" value="大宗原材料" label="大宗原材料"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="MaterialSkuId_FormItem" prop="MaterialSkuId">
								<template #label>
									<WtmLabelTooltip label="物料规格" tooltip="物料的具体规格型号" />
								</template>
								<el-select v-model="searchData.MaterialSkuId" :data="stateData.AllSysMaterialSkus" clearable>
									<el-option v-for="item in stateData.AllSysMaterialSkus" :key="item.Value" :value="item.Value" :label="item.Text"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="GroupId_FormItem" prop="GroupId">
								<template #label>
									<WtmLabelTooltip label="申请部门" tooltip="申请采购的部门" />
								</template>
								<el-select v-model="searchData.GroupId" :data="stateData.AllSysGroups" clearable>
									<el-option v-for="item in stateData.AllSysGroups" :key="item.Value" :value="item.Value" :label="item.Text"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="RequestBy_FormItem" prop="RequestBy">
								<template #label>
									<WtmLabelTooltip label="申请人" tooltip="采购需求的申请人" />
								</template>
								<el-input v-model="searchData.RequestBy" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="RequiredDeliveryDate_FormItem" prop="RequiredDeliveryDate">
								<template #label>
									<WtmLabelTooltip label="要求到货日期" tooltip="要求的到货日期" />
								</template>
								<el-date-picker v-model="searchData.RequiredDeliveryDate" clearable></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="EntryDate_FormItem" prop="EntryDate">
								<template #label>
									<WtmLabelTooltip label="入池日期" tooltip="需求进入需求池的日期" />
								</template>
								<el-date-picker v-model="searchData.EntryDate" clearable></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="PurchaseStrategy_FormItem" prop="PurchaseStrategy">
								<template #label>
									<WtmLabelTooltip label="采购策略" tooltip="采购策略：询比价、招投标、协议采购" />
								</template>
								<el-select v-model="searchData.PurchaseStrategy" clearable>
									<el-option key="询比价" value="询比价" label="询比价"></el-option>
									<el-option key="招投标" value="招投标" label="招投标"></el-option>
									<el-option key="协议采购" value="协议采购" label="协议采购"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="MaterialName_FormItem" prop="MaterialName">
								<template #label>
									<WtmLabelTooltip label="物料名称" tooltip="物料的名称" />
								</template>
								<el-input v-model="searchData.MaterialName" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="MaterialCode_FormItem" prop="MaterialCode">
								<template #label>
									<WtmLabelTooltip label="物料编码" tooltip="物料的编码" />
								</template>
								<el-input v-model="searchData.MaterialCode" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="MaterialSkuName_FormItem" prop="MaterialSkuName">
								<template #label>
									<WtmLabelTooltip label="物料SKU名称" tooltip="物料SKU的名称" />
								</template>
								<el-input v-model="searchData.MaterialSkuName" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="MaterialSkuCode_FormItem" prop="MaterialSkuCode">
								<template #label>
									<WtmLabelTooltip label="物料SKU编码" tooltip="物料SKU的编码" />
								</template>
								<el-input v-model="searchData.MaterialSkuCode" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ErpId_FormItem" prop="ErpId">
								<template #label>
									<WtmLabelTooltip label="ERP系统编码" tooltip="ERP系统的编码" />
								</template>
								<el-input v-model="searchData.ErpId" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="RequestBillCode_FormItem" prop="RequestBillCode">
								<template #label>
									<WtmLabelTooltip label="采购申请单编号" tooltip="采购申请单的编号" />
								</template>
								<el-input v-model="searchData.RequestBillCode" clearable></el-input>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysPurchaseRequirementPoolEntry/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysPurchaseRequirementPoolEntry/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysPurchaseRequirementPoolEntry/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysPurchaseRequirementPoolEntry/SysPurchaseRequirementPoolEntryExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysPurchaseRequirementPoolEntry/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysPurchaseRequirementPoolEntry/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysPurchaseRequirementPoolEntry/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="采购需求池明细;true;HengTong.Areas.SupplyChain.Controllers;SysPurchaseRequirementPoolEntry">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysPurchaseRequirementPoolEntryApi as api } from '/@/views/supplychain/syspurchaserequirementpoolentry/api';
import {
	ISysPurchaseRequirementPoolEntryView,
	ISysPurchaseRequirementPoolEntryQuery,
} from '/@/views/supplychain/syspurchaserequirementpoolentry/api/interface';
import other from '/@/utils/other';
import { IViewModel, ISysSelectType } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysPurchaseRequirementPoolEntryQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const stateData = reactive({
	AllSysPurchaseRequirementPools: [] as ISysSelectType[],
	AllSysPurchaseRequestBills: [] as ISysSelectType[],
	AllSysMaterials: [] as ISysSelectType[],
	AllSysMaterialSkus: [] as ISysSelectType[],
	AllSysGroups: [] as ISysSelectType[],
});

const searchData = ref<ISysPurchaseRequirementPoolEntryQuery>({
	PoolId: null,
	RequestBillId: null,
	MaterialId: null,
	MaterialSkuId: null,
	GroupId: null,
	RequestBy: null,
	PurchaseType: null,
	MaterialType: null,
	RequiredDeliveryDate: null,
	EntryDate: null,
	PurchaseState: null,
	PurchaseStrategy: null,
	MaterialName: null,
	MaterialCode: null,
	MaterialSkuName: null,
	MaterialSkuCode: null,
	ErpId: null,
	RequestBillCode: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）- 按重要程度排序
	header: [
		{ title: '物料', key: 'MaterialName', type: 'text', isCheck: true },
		{ title: '物料Sku', key: 'MaterialSkuName', type: 'text', isCheck: true },
		{ title: '采购状态', key: 'PurchaseState', type: 'text', isCheck: true },
		{ title: '申请数量', key: 'RequestQuantity', type: 'text', isCheck: true },
		{ title: '已采购数量', key: 'PurchasedQuantity', type: 'text', isCheck: true },
		{ title: '剩余数量', key: 'RemainingQuantity', type: 'text', isCheck: true },
		{ title: '预计单价', key: 'EstimatedPrice', type: 'text', isCheck: true },
		{ title: '预算金额', key: 'BudgetAmount', type: 'text', isCheck: true },
		{ title: '采购类型', key: 'PurchaseType', type: 'text', isCheck: true },
		{ title: '物料类型', key: 'MaterialType', type: 'text', isCheck: true },
		{ title: '紧急程度', key: 'UrgencyLevel', type: 'text', isCheck: true },
		{ title: '要求到货日期', key: 'RequiredDeliveryDate', type: 'text', isCheck: true },
		{ title: '需求池', key: 'PoolName', type: 'text', isCheck: true },
		{ title: '采购申请单', key: 'RequestBillName', type: 'text', isCheck: true },
		{ title: '申请单明细', key: 'RequestBillEntryName', type: 'text', isCheck: true },
		{ title: '申请部门', key: 'GroupName', type: 'text', isCheck: true },
		{ title: '申请人', key: 'RequestBy', type: 'text', isCheck: true },
		{ title: '采购策略', key: 'PurchaseStrategy', type: 'text', isCheck: true },
		{ title: '审批通过日期', key: 'ApprovalDate', type: 'text', isCheck: true },
		{ title: '入池日期', key: 'EntryDate', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	// 如果有 entityId（从主表传入），自动设置为 PoolId 进行过滤
	if (props.entityId) {
		searchData.value.PoolId = props.entityId as string;
	}
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	// 如果有 entityId，将其作为 PoolId 传递给创建对话框，确保新明细自动关联到主表
	const wtmdata: any = props.entityId ? { PoolId: props.entityId } : {};
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, wtmdata, getTableData);
};

const OnEditRowClick = (row: ISysPurchaseRequirementPoolEntryView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysPurchaseRequirementPoolEntryView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysPurchaseRequirementPoolEntryView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysPurchaseRequirementPoolEntryView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	const promises: Promise<any>[] = [
		other
			.getSelectList('/api/SysPurchaseRequirementPoolEntry/GetSysPurchaseRequirementPools', [], false)
			.then((x) => (stateData.AllSysPurchaseRequirementPools = x)),
		other
			.getSelectList('/api/SysPurchaseRequirementPoolEntry/GetSysPurchaseRequestBills', [], false)
			.then((x) => (stateData.AllSysPurchaseRequestBills = x)),
		// other.getSelectList('/api/SysPurchaseRequirementPoolEntry/GetSysMaterials', [], false).then((x) => (stateData.AllSysMaterials = x)),
		// other.getSelectList('/api/SysPurchaseRequirementPoolEntry/GetSysMaterialSkus', [], false).then((x) => (stateData.AllSysMaterialSkus = x)),
		// other.getSelectList('/api/SysPurchaseRequirementPoolEntry/GetSysGroups', [], false).then((x) => (stateData.AllSysGroups = x)),

		getTableData(),
	];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
